package com.moyu.article.service.impl;

import com.github.pagehelper.PageHelper;
import com.moyu.article.domain.board.Board;
import com.moyu.article.domain.board.dto.*;
import com.moyu.article.domain.board.vo.BoardHotVO;
import com.moyu.article.domain.board.vo.BoardVO;
import com.moyu.article.domain.post.Post;
import com.moyu.article.domain.post.vo.BoardOptionVO;
import com.moyu.article.domain.post.vo.PostListVO;
import com.moyu.article.mapper.BoardMapper;
import com.moyu.article.service.IBoardService;
import com.moyu.common.core.enums.ResultCode;
import com.moyu.common.security.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 赵彦博
 * @Date 2025/3/29 19:05
 */
@Service
public class BoardServiceImpl implements IBoardService {

    @Autowired
    private BoardMapper boardMapper;

    @Override
    public List<BoardVO> getBoardList(BoardQueryDTO boardQueryDTO) {
        // 设置默认排序
        if (StringUtils.isBlank(boardQueryDTO.getSortOrder())) {
            boardQueryDTO.setSortOrder("asc");
        }
        PageHelper.startPage(boardQueryDTO.getPageNum(), boardQueryDTO.getPageSize());
        return boardMapper.getBoardList(boardQueryDTO);
    }

    @Override
    @Transactional
    public int addBoard(BoardAddDTO boardAddDTO) {
        // 1. 获取当前最大排序值
        Integer maxSort = boardMapper.selectMaxSort();

        // 2. 构建Board实体
        Board board = new Board();
        board.setBoardName(boardAddDTO.getBoardName());
        board.setSort(maxSort != null ? maxSort + 1 : 1); // 自动设置排序值为最大值+1
        board.setState(boardAddDTO.getState());

        // 3. 执行插入
        return boardMapper.insert(board);
    }

    @Override
    @Transactional
    public int updateBoardService(BoardUpdateDTO boardUpdateDTO) {
        // 将String类型的boardId转为Long
        Long boardId = Long.parseLong(boardUpdateDTO.getBoardId());

        // 1. 检查标签是否存在
        Board existingBoard = boardMapper.selectById(boardUpdateDTO.getBoardId());
        if (existingBoard == null) {
            throw new RuntimeException("标签不存在，ID: " + boardUpdateDTO.getBoardId());
        }

        // 2. 处理排序值为null的情况
        if (existingBoard.getSort() == null) {
            // 如果原排序为null，设置为当前最大值+1
            Integer maxSort = boardMapper.selectMaxSort();
            existingBoard.setSort(maxSort != null ? maxSort + 1 : 1);
            boardMapper.updateById(existingBoard); // 先更新排序值
        }

        // 3. 获取原排序值（此时保证不为null）
        Integer originalSort = existingBoard.getSort();
        Integer newSort = boardUpdateDTO.getSort();

        // 4. 如果排序值有变化，调整其他记录的排序
        if (newSort != null && !newSort.equals(originalSort)) {
            newSort = Math.max(1, newSort); // 确保不小于1

            if (newSort > originalSort) {
                boardMapper.decreaseSortBetween(originalSort + 1, newSort, boardId);
            } else {
                boardMapper.increaseSortBetween(newSort, originalSort - 1, boardId);
            }
        }

        // 5. 更新当前记录
        Board updateBoard = new Board();
        updateBoard.setBoardId(Long.valueOf(boardId));
        updateBoard.setBoardName(boardUpdateDTO.getBoardName());
        updateBoard.setDescription(boardUpdateDTO.getDescription());
        updateBoard.setSort(newSort != null ? newSort : originalSort);
        updateBoard.setState(boardUpdateDTO.getState());

        return boardMapper.updateById(updateBoard);
    }


    @Override
    @Transactional
    public int batchUpdateSort(List<BatchSortUpdateDTO> updateList) {
        if (updateList == null || updateList.isEmpty()) {
            return 0;
        }

        // 检查ID是否存在
        List<Long> ids = updateList.stream()
                .map(dto -> Long.parseLong(dto.getBoardId()))
                .collect(Collectors.toList());

        if (boardMapper.selectCountByIds(ids) != ids.size()) {
            throw new RuntimeException("包含不存在的标签ID");
        }

        // 执行批量更新
        return boardMapper.batchUpdateSort(updateList);
    }

    @Override
    public int deleteBoard(Long boardId) {
        if (hasAssociatedPosts(boardId)) {
            throw new ServiceException(ResultCode.FAILED_DELETE_BOARD);
        }
        return boardMapper.deleteById(boardId);
    }

    @Override
    public List<BoardOptionVO> getBoardOptions() {
        return boardMapper.selectBoardOptions();
    }

    @Override
    public List<BoardVO> getAllBoard(BoardAllQueryDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<BoardVO> boards = boardMapper.getAllBoard(dto);
        if (boards != null) {
            boards.forEach(board -> board.setSelected(false));
        }
        return boards;
    }

    @Override
    public List<BoardHotVO> getHotBoard() {
        return boardMapper.getHotBoard();
    }

    @Override
    public List<PostListVO> listByBoardId(BoardDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return boardMapper.listByBoardId(dto.getBoardId());
    }

    @Override
    public BoardVO detailByBoardId(String boardId) {
        return boardMapper.detailByBoardId(boardId);
    }

    public boolean hasAssociatedPosts(Long boardId) {
        return boardMapper.countAssociatedPosts(boardId) > 0;
    }
}
